<template>
  <Modal
    :visible="visible"
    :title="(type === 2 ? '编辑' : '新增') + '组织'"
    :width="600"
    @ok="handleOk"
    @cancel="handleCancel()"
  >
    <template #footer>
      <Button key="back" @click="handleCancel()">返回</Button>
      <Button key="submit" type="primary" @click="handleOk">确认</Button>
    </template>
    <div class="centent">
      <Form ref="formRef" :model="formState" :rules="rules" :labelCol="{ span: 4 }" :wrapper-col="wrapperCol">
        <FormItem label="组织名称" name="name">
          <Input v-model:value="formState.name" />
        </FormItem>
        <FormItem label="组织编码" name="code">
          <Input v-model:value="formState.code" />
        </FormItem>
        <FormItem label="上级组织" name="parentId">
          <TreeSelect
            v-model:value="formState.parentId"
            style="width: 100%"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :fieldNames="replaceFields"
            :tree-data="treeData"
            placeholder="请选择组织"
            @select="selectOrg"
            :disabled="type !== 1 && type !== 2"
          >
          </TreeSelect>
        </FormItem>
        <FormItem label="描述" name="description">
          <Textarea v-model:value="formState.description" />
        </FormItem>
      </Form>
    </div>
  </Modal>
</template>
<script lang="ts" setup>
import { ref, defineProps, reactive, watch } from 'vue';
import { Form, Modal, FormItem, Input, message, TreeSelect, Textarea, Button } from 'ant-design-vue';
import { createOrg, updateOrg, getSaaSOrgTree } from '/@/api/organization-mgmt/organization';
import { SaaSOrgItem } from '/@/api/organization-mgmt/model/organizationModel';
interface FormState {
  id: string;
  parentId: string;
  tenantCode: string;
  isBuiltIn: boolean;
  idaasOrgId: string;
  // oneaccessOrgId: string;
  name: string;
  code: string;
  description: string;
}
const formRef = ref();
// 接收父组件的值
let props = defineProps({
  visible: Boolean,
  type: Number,
  org: Object,
});
const wrapperCol = { span: 14 };
const rules = {
  name: [
    { required: true, message: '请输入组织名称', trigger: 'blur' },
    { min: 3, max: 30, message: 'Length should be 3 to 30', trigger: 'blur' },
  ],
  code: [
    {
      required: true,
      message: '请输入组织编码',
      trigger: 'blur',
    },
  ],
  parentId: [
    {
      required: true,
      message: '请选择上级组织',
      trigger: 'change',
    },
  ],
};

const replaceFields = {
  children: 'children',
  label: 'name',
  value: 'id',
};
let visible = ref(props.visible);
let formState = reactive<Partial<FormState>>({});
let propsRef = reactive(props);
let type = ref(props.type);
const treeData = ref<Partial<SaaSOrgItem[]>>([]);
async function fetchOrgTree() {
  const res = await getSaaSOrgTree();
  treeData.value = res;
}
const selectOrg = (val: string) => {
  formState.parentId = val;
};
watch(propsRef, (newValue) => {
  visible.value = newValue.visible;
  type.value = newValue.type;
  if (newValue.visible) {
    fetchOrgTree();
  }
  // 新增
  if (type.value === 1) {
    formState.name = '';
    formState.code = '';
    formState.parentId = '';
    formState.description = '';
    formState.isBuiltIn = false;
  }
  // 编辑
  if (type.value === 2) {
    formState.id = newValue.org?.id;
    formState.name = newValue.org?.name;
    formState.code = newValue.org?.code;
    formState.parentId = newValue.org?.parentId;
    formState.description = newValue.org?.description;
    formState.isBuiltIn = newValue.org?.isBuiltIn;
  }
  // 新增下级
  if (type.value === 3) {
    formState.name = '';
    formState.code = '';
    formState.parentId = newValue.org?.id;
    formState.description = '';
    formState.isBuiltIn = false;
  }
  formState.idaasOrgId = newValue.org?.idaasOrgId;
});
const emit = defineEmits(['close']);

const handleCancel = () => {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  emit('close', 'close');
};

const handleOk = async () => {
  formRef.value.validate().then(async () => {
    if (type.value === 2) {
      const res = await updateOrg(formState);
      if (res) {
        message.success('组织编辑成功！');
        emit('close', 'success');
      } else {
        message.error('组织编辑失败！');
        emit('close', 'close');
      }
    } else {
      const res = await createOrg(formState);
      if (res) {
        message.success('组织创建成功！');
        emit('close', 'success');
      } else {
        message.error('组织创建失败！');
        emit('close', 'close');
      }
    }
  });
};
</script>
<style lang="less"></style>
